package com.ruoyi.wb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WxV3PayConfig;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.wx.WXPaySignatureCertificateUtil;
import com.ruoyi.common.utils.wx.WXPayUtil;
import com.ruoyi.common.utils.wx.WxMiniPayUtils;
import com.ruoyi.system.domain.vo.OrderSummaryVo;
import com.ruoyi.wb.domain.*;
import com.ruoyi.wb.dto.DeviceRenewInfoDto;
import com.ruoyi.wb.dto.WbRepairApplyDto;
import com.ruoyi.wb.enmus.RoleNameEnums;
import com.ruoyi.wb.enmus.WbRepairApplyOrderType;
import com.ruoyi.wb.mapper.WbMaintainCompanyUserMapper;
import com.ruoyi.wb.mapper.WbRepairApplyMapper;
import com.ruoyi.wb.mapper.WbRepairOrderMapper;
import com.ruoyi.wb.service.IWbEntAuthService;
import com.ruoyi.wb.service.IWbRepairApplyService;
import com.ruoyi.wb.service.IWbRepairOrderService;
import com.ruoyi.wb.vo.WbRepairOrderVo;
import com.wechat.pay.contrib.apache.httpclient.notification.Notification;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationRequest;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 维修订单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-14
 */
@Service
public class WbRepairOrderServiceImpl implements IWbRepairOrderService {
    @Autowired
    private WbRepairOrderMapper wbRepairOrderMapper;

    @Autowired
    private WbRepairApplyMapper wbRepairApplyMapper;

    @Autowired
    private WbMaintainCompanyUserMapper wbMaintainCompanyUserMapper;

    @Autowired
    private IWbRepairApplyService wbRepairApplyService;

    @Autowired
    private IWbEntAuthService wbEntAuthService;




    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 查询维修订单
     *
     * @param id 维修订单主键
     * @return 维修订单
     */
    @Override
    public WbRepairOrderVo selectWbRepairOrderById(String id) {
        WbRepairOrder wbRepairOrder = wbRepairOrderMapper.selectWbRepairOrderById(id);
        WbRepairOrderVo wbRepairOrderVo = BeanUtil.copyProperties(wbRepairOrder, WbRepairOrderVo.class);
        if (!ObjectUtils.isEmpty(wbRepairOrder) && !ObjectUtils.isEmpty(wbRepairOrder.getApplyId())) {
            WbRepairApply wbRepairApply = wbRepairApplyMapper.selectWbRepairApplyById(wbRepairOrder.getApplyId());
            wbRepairOrderVo.setWbRepairApply(wbRepairApply);
        }
        if (!ObjectUtils.isEmpty(wbRepairOrder) && StringUtils.isNotEmpty(wbRepairOrder.getDeviceRenewInfo())) {
            wbRepairOrderVo.setDeviceRenewInfoDtos(JSONUtil.toList(wbRepairOrder.getDeviceRenewInfo(), DeviceRenewInfoDto.class));


        }

        return wbRepairOrderVo;
    }

    /**
     * 查询维修订单列表
     *
     * @param wbRepairOrder 维修订单
     * @return 维修订单
     */
    @Override
    public List<WbRepairOrderVo> selectWbRepairOrderList(WbRepairOrder wbRepairOrder) {
        //普通用户能查看   超级管理员能查看   维保公司管理员能查看
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        if (CollectionUtils.isEmpty(roles)) {
            return new ArrayList<WbRepairOrderVo>();
        }
        for (SysRole role : roles) {
            if (role.getRoleName().equals(RoleNameEnums.REPAIR_MAN.getDescribe())) {//外部维修师傅
                wbRepairOrder.setRepairerId(user.getUserId());
            }
            if (role.getRoleName().equals(RoleNameEnums.DOMESTIC_CONSUMER.getDescribe())) {//普通角色
                wbRepairOrder.setUserId(user.getUserId());
            }
        }
        //查询当前用户有没有维保公司

        List<WbEntAuth> wbEntAuthList = wbEntAuthService.selectWbEntAuthListByUserId(user.getUserId());
        if (!CollectionUtils.isEmpty(wbEntAuthList)) {
            wbRepairOrder.setBusinessId(wbEntAuthList.get(0).getMaintainCompanyId());
        }


        List<WbRepairOrder> wbRepairOrders = wbRepairOrderMapper.selectWbRepairOrderList(wbRepairOrder);
        if (CollectionUtils.isEmpty(wbRepairOrders)) {
            return BeanUtil.copyToList(wbRepairOrders, WbRepairOrderVo.class);
        }
        Map<String, String> wbRepairOrderMap = wbRepairOrders.stream().collect(Collectors.toMap(WbRepairOrder::getId, item -> {
            if (StringUtils.isEmpty(item.getDeviceRenewInfo())) {
                return "";
            }
            return item.getDeviceRenewInfo();

        }));
        //转换vo
        List<WbRepairOrderVo> wbRepairOrderVos = BeanUtil.copyToList(wbRepairOrders, WbRepairOrderVo.class);
        wbRepairOrderVos.forEach(item -> {
            if (StringUtils.isNotEmpty(wbRepairOrderMap.get(item.getId()))) {
                item.setDeviceRenewInfoDtos(JSONUtil.toList(wbRepairOrderMap.get(item.getId()), DeviceRenewInfoDto.class));
            }

        });
        Map<Long, WbRepairOrderVo> wbRepairOrderVoMap = wbRepairOrderVos.stream().collect(Collectors.toMap(WbRepairOrderVo::getApplyId, item -> item));
        List<Long> ids = wbRepairOrders.stream().map(WbRepairOrder::getApplyId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(ids)) {
            List<WbRepairApply> wbRepairApplyList = wbRepairApplyMapper.selectWbRepairApplyByIds(ids);
            for (WbRepairApply wbRepairApply : wbRepairApplyList) {
                WbRepairOrderVo wbRepairOrderVo = wbRepairOrderVoMap.get(wbRepairApply.getId());
                wbRepairOrderVo.setWbRepairApply(wbRepairApply);
            }
        }

        ArrayList<WbRepairOrderVo> result = new ArrayList<>(wbRepairOrderVoMap.values());
        result.sort(new Comparator<WbRepairOrderVo>() {
            @Override
            public int compare(WbRepairOrderVo o1, WbRepairOrderVo o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });
        return result;

    }

    /**
     * 查询维修订单列表总条数
     */
    @Override
    public int selectWbRepairOrderListCount(WbRepairOrder wbRepairOrder) {
        //普通用户能查看   超级管理员能查看   维保公司管理员能查看
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        if (CollectionUtils.isEmpty(roles)) {
            return 0;
        }
        for (SysRole role : roles) {
            if (role.getRoleName().equals(RoleNameEnums.REPAIR_MAN.getDescribe())) {//外部维修师傅
                wbRepairOrder.setRepairerId(user.getUserId());
            }
            if (role.getRoleName().equals(RoleNameEnums.DOMESTIC_CONSUMER.getDescribe())) {//普通角色
                wbRepairOrder.setUserId(user.getUserId());
            }
        }
        //查询当前用户有没有维保公司

        List<WbEntAuth> wbEntAuthList = wbEntAuthService.selectWbEntAuthListByUserId(user.getUserId());
        if (!CollectionUtils.isEmpty(wbEntAuthList)) {
            wbRepairOrder.setBusinessId(wbEntAuthList.get(0).getMaintainCompanyId());
        }

        return wbRepairOrderMapper.selectWbRepairOrderListCount(wbRepairOrder);

    }




    @Override
    public List<WbRepairOrderVo> selectWbRepairOrderWbList(WbRepairOrder wbRepairOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        for (SysRole role : roles) {
            if (role.getRoleName().equals(RoleNameEnums.MAINTAIN_STAFF.getDescribe()) ||//维保人员
                    role.getRoleName().equals(RoleNameEnums.ENGINEER.getDescribe())//工程师
            ) {//维保人员 维保公司的维修师傅
                wbRepairOrder.setRepairerId(user.getUserId());
            } else if (role.getRoleName().equals(RoleNameEnums.MAINTAIN_ADMIN.getDescribe())) {//维保公司管理员
                WbMaintainCompanyUser wbMaintainCompanyUser = new WbMaintainCompanyUser();
                wbMaintainCompanyUser.setUserId(user.getUserId());
                List<WbMaintainCompanyUser> wbMaintainCompanyUserList = wbMaintainCompanyUserMapper.selectWbMaintainCompanyUserList(wbMaintainCompanyUser);
                if (!CollectionUtils.isEmpty(wbMaintainCompanyUserList)) {
                    wbRepairOrder.setRepairerId(null);
                    wbRepairOrder.setBusinessId(wbMaintainCompanyUserList.get(0).getMaintainCompanyId());
                }
            }
        }
        List<WbRepairOrder> wbRepairOrders = wbRepairOrderMapper.selectWbRepairOrderWbList(wbRepairOrder);
        if (CollectionUtils.isEmpty(wbRepairOrders)) {

            return BeanUtil.copyToList(wbRepairOrders, WbRepairOrderVo.class);
        }
        Map<String, String> wbRepairOrderMap = wbRepairOrders.stream().collect(Collectors.toMap(WbRepairOrder::getId, item -> {
            if (StringUtils.isEmpty(item.getDeviceRenewInfo())) {
                return "";
            }
            return item.getDeviceRenewInfo();

        }));
        //转换vo
        List<WbRepairOrderVo> wbRepairOrderVos = BeanUtil.copyToList(wbRepairOrders, WbRepairOrderVo.class);
        wbRepairOrderVos.forEach(item -> {
            if (StringUtils.isNotEmpty(wbRepairOrderMap.get(item.getId()))) {
                item.setDeviceRenewInfoDtos(JSONUtil.toList(wbRepairOrderMap.get(item.getId()), DeviceRenewInfoDto.class));
            }

        });
        Map<Long, WbRepairOrderVo> wbRepairOrderVoMap = wbRepairOrderVos.stream().collect(Collectors.toMap(WbRepairOrderVo::getApplyId, item -> item));
        List<Long> ids = wbRepairOrders.stream().map(WbRepairOrder::getApplyId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(ids)) {
            List<WbRepairApply> wbRepairApplyList = wbRepairApplyMapper.selectWbRepairApplyByIds(ids);
            for (WbRepairApply wbRepairApply : wbRepairApplyList) {
                WbRepairOrderVo wbRepairOrderVo = wbRepairOrderVoMap.get(wbRepairApply.getId());
                wbRepairOrderVo.setWbRepairApply(wbRepairApply);
            }
        }
        ArrayList<WbRepairOrderVo> result = new ArrayList<>(wbRepairOrderVoMap.values());
        result.sort(new Comparator<WbRepairOrderVo>() {
            @Override
            public int compare(WbRepairOrderVo o1, WbRepairOrderVo o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });
        return result;
    }

    @Override
    public int selectWbRepairOrderWbListCount(WbRepairOrder wbRepairOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        for (SysRole role : roles) {
            if (role.getRoleName().equals(RoleNameEnums.MAINTAIN_STAFF.getDescribe()) ||//维保人员
                    role.getRoleName().equals(RoleNameEnums.ENGINEER.getDescribe())//工程师
            ) {//维保人员 维保公司的维修师傅
                wbRepairOrder.setRepairerId(user.getUserId());
            } else if (role.getRoleName().equals(RoleNameEnums.MAINTAIN_ADMIN.getDescribe())) {//维保公司管理员
                WbMaintainCompanyUser wbMaintainCompanyUser = new WbMaintainCompanyUser();
                wbMaintainCompanyUser.setUserId(user.getUserId());
                List<WbMaintainCompanyUser> wbMaintainCompanyUserList = wbMaintainCompanyUserMapper.selectWbMaintainCompanyUserList(wbMaintainCompanyUser);
                if (!CollectionUtils.isEmpty(wbMaintainCompanyUserList)) {
                    wbRepairOrder.setRepairerId(null);
                    wbRepairOrder.setBusinessId(wbMaintainCompanyUserList.get(0).getMaintainCompanyId());
                }
            }
        }
        return wbRepairOrderMapper.selectWbRepairOrderWbListCount(wbRepairOrder);
    }

    /**
     * 新增维修订单
     *
     * @param wbRepairOrder 维修订单
     * @return 结果
     */
    @Override
    public int insertWbRepairOrder(WbRepairOrder wbRepairOrder) {
        wbRepairOrder.setCreateTime(DateUtils.getNowDate());
        return wbRepairOrderMapper.insertWbRepairOrder(wbRepairOrder);
    }

    /**
     * 修改维修订单
     *
     * @param wbRepairOrder 维修订单
     * @return 结果
     */
    @Override
    public int updateWbRepairOrder(WbRepairOrder wbRepairOrder) {
        wbRepairOrder.setUpdateTime(DateUtils.getNowDate());
        return wbRepairOrderMapper.updateWbRepairOrder(wbRepairOrder);
    }

    /**
     * 批量删除维修订单
     *
     * @param ids 需要删除的维修订单主键
     * @return 结果
     */
    @Override
    public int deleteWbRepairOrderByIds(String[] ids) {
        return wbRepairOrderMapper.deleteWbRepairOrderByIds(ids);
    }

    /**
     * 删除维修订单信息
     *
     * @param id 维修订单主键
     * @return 结果
     */
    @Override
    public int deleteWbRepairOrderById(String id) {
        return wbRepairOrderMapper.deleteWbRepairOrderById(id);
    }


    @Override
    @Transactional
    public Map<String, Object> wxPayOrder(WbRepairOrder wbRepairOrder) {
        //zyOrder = zyOrderMapper.selectZyOrderById(baOrder.getId());
//        baOrder.setTotalFee(((baOrder.getPrice()).multiply(new BigDecimal(baOrder.getTotalNum()))).setScale(2, RoundingMode.HALF_UP));
//        baOrder.setCreateData(new Date());
//        //baOrder.setUserId(SecurityUtils.getUserId());
//        baOrder.setUserId(SecurityUtils.getUserId());
//        baOrder.setOrderNum(System.currentTimeMillis()+""+ new Random().nextInt(10000));
//        baOrderMapper.insertBaOrder(baOrder);
        //wbRepairOrder.setPayOrdernumber(System.currentTimeMillis()+""+ new Random().nextInt(10000));
        //this.updateWbRepairOrder(wbRepairOrder);
        Map<String, Object> map = this.wxPay(wbRepairOrder);
//        if(map.get("message").equals("下单失败")){
//            throw new Exception("自定义异常信息");
//        }
        return map;
    }


    //微信支付
    @Override
    public Map<String, Object> wxPay(WbRepairOrder wbRepairOrder) {
        WbRepairOrder order = wbRepairOrderMapper.selectWbRepairOrderById(wbRepairOrder.getId());

        if (ObjectUtils.isEmpty(order)) {
            throw new RuntimeException("订单不存在");
        }


        Map<String, Object> map = new HashMap<>();
        //微信支付
        //支付总金额
        // BigDecimal totalPrice = BigDecimal.ZERO;
        //设置支付金额
        //转换金额保留两位小数点

        //    Double moneyDouble =baOrder.getTotalFee().doubleValue() * 100 ;
        String money = new BigDecimal(order.getPayMoney()).multiply(new BigDecimal(100)).toString();
        money= money.substring(0,money.indexOf("."));


//        Double moneyDouble=1.00;
//        int money = (int) Math.floor(moneyDouble);
        try {
            String body = "消易云";
            //完成签名并执行请求
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            // BaUser bauser=new BaUser();
            //  bauser.setSysUserid(SecurityUtils.getUserId());
            ///   bauser.setSysUserid(SecurityUtils.getUserId());
            //生成 vx订单id
            String vxpayOrdernumber = IdUtil.simpleUUID();
            order.setVxpayOrdernumber(vxpayOrdernumber);
            int i = wbRepairOrderMapper.updateWbRepairOrder(order);
            System.out.println("vxpayOrdernumber------------------XXXXXXXXXXXXXXX" +
                    "---------------------------------- = " + vxpayOrdernumber);
            if (i == 0) {
                throw new RuntimeException("修改订单失败");
            }
            String openid = sysUser.getOpenId();
            JSONObject response = WxMiniPayUtils.creatOrderJSAPI(openid, vxpayOrdernumber,Integer.parseInt(money) , body);
            //int statusCode = response.getStatusLine().getStatusCode();
            log.info("+++++++wx支付response++++++++++++" + response);
            String bodyResult = response.getString("body");
            JSONObject object = JSONObject.parseObject(bodyResult);
            String prepayId = object.getString("prepay_id");
            if (StringUtils.isNotEmpty(prepayId)) { //处理成功
                //  String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                //   JSONObject object = JSONObject.parseObject(result);
                //获取预付单
                // String prepayId = object.getString("prepay_id");
                //生成签名
                Long timestamp = System.currentTimeMillis() / 1000;
                //随机字符串 这个是微信支付maven自带的 也可以用其它的
                String nonceStr = WXPayUtil.generateNonceStr();
                //生成带签名支付信息
                Map<String, String> param = new HashMap<>();
                param.put("appid", WxV3PayConfig.APP_ID);
                param.put("partnerid", WxV3PayConfig.Mch_ID);
                param.put("packageValue", prepayId);
//                param.put("package", "Sign=WXPay");
                param.put("package", "prepay_id=" + prepayId);
                param.put("nonceStr", nonceStr);
                param.put("timestamp", String.valueOf(timestamp));
                param.put("signType", "MD5");
                // 加密串中包括 appId timeStamp nonceStr package signType 5个参数, 通过sdk WXPayUtil类加密, 注意, 此处使用  MD5加密  方式
                String signatureStr = Stream.of(WxV3PayConfig.APP_ID, String.valueOf(timestamp), nonceStr, "prepay_id=" + prepayId)
                        .collect(Collectors.joining("\n", "", "\n"));
                String sign = WXPayUtil.getSign(signatureStr, WxV3PayConfig.privateKey_Path);
                //String sign = WXPayUtil.getSign(signatureStr, "/www/wwwroot/zhongyi/java/wxPay/apiclient_key.pem");
                //  String sign = WXPayUtil.getSign(signatureStr, "/www/wwwroot/boaomeidi/java/apiclient_key.pem");
                param.put("orderNum", order.getPayOrdernumber());
                param.put("paySign", sign);
                map.put("code", 200);
                map.put("message", "下单成功");
                map.put("data", param);
                return map;
            }
            map.put("code", 200);
            map.put("message", "下单失败");
            map.put("data", response);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 200);
            map.put("message", "下单失败:" + e.getMessage());
            return map;
        }

    }


    @Override
    @Transactional
    public Map<String, Object> payNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("+++++++支付回调开始++++++++++++" + response);
        Map<String, Object> map = new HashMap<>();
        try {
            BufferedReader br = request.getReader();
            String str = null;
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            // 构建request，传入必要参数
//            NotificationRequest requests = new NotificationRequest.Builder()
//                    .withSerialNumber(request.getHeader("Wechatpay-Serial"))
//                    .withNonce(request.getHeader("Wechatpay-Nonce"))
//                    .withTimestamp(request.getHeader("Wechatpay-Timestamp"))
//                    .withSignature(request.getHeader("Wechatpay-Signature"))
//                    .withBody(String.valueOf(sb))
//                    .build();
//            //验签
//            NotificationHandler handler = new NotificationHandler(WXPaySignatureCertificateUtil.getVerifier(WxV3PayConfig.mchSerialNo), WxV3PayConfig.apiV3Key.getBytes(StandardCharsets.UTF_8));
//            //解析请求体
//            Notification notification = handler.parse(requests);
//            String decryptData = notification.getDecryptData();


            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(request.getHeader("Wechatpay-Serial"))
                    .nonce(request.getHeader("Wechatpay-Nonce"))
                    .signature(request.getHeader("Wechatpay-Signature"))
                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
                    .body(sb.toString())
                    .build();

// 如果已经初始化了 RSAAutoCertificateConfig，可直接使用
// 没有的话，则构造一个
//            NotificationConfig config = new RSAAutoCertificateConfig.Builder()
//                    .merchantId(WxV3PayConfig.Mch_ID)
//                    .privateKeyFromPath(WxV3PayConfig.privateKey_Path)
//                    .merchantSerialNumber(WxV3PayConfig.mchSerialNo)
//                    .apiV3Key(WxV3PayConfig.apiV3Key)
//                    .build();
            NotificationConfig config =
                    new RSAPublicKeyConfig.Builder()
                            .merchantId(WxV3PayConfig.Mch_ID)
                            .privateKeyFromPath(WxV3PayConfig.privateKey_Path)
                            .publicKeyFromPath(WxV3PayConfig.publicKey_Path)
                            .publicKeyId(WxV3PayConfig.PUB_KEY_ID)
                            .merchantSerialNumber(WxV3PayConfig.mchSerialNo)
                            .apiV3Key(WxV3PayConfig.apiV3Key)
                            .build();
// 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(config);
            log.info("+++++++支付回调开始++++++++++++111111111111111" + parser);
            WxResult parseResult = parser.parse(requestParam, WxResult.class);
            System.out.println("parseResult = " + parseResult.getOut_trade_no());
            log.info("+++++++支付回调开始++++++++++++2222222222222222" + parseResult);
            //解析
            //JSONObject jsonObject = JSONObject.parseObject(parseResult.toString());
            //支付状态交易状态，枚举值： SUCCESS：支付成功 REFUND：转入退款 NOTPAY：未支付 CLOSED：已关闭 REVOKED：已撤销（付款码支付）
            // USERPAYING：用户支付中（付款码支付） PAYERROR：支付失败(其他原因，如银行返回失败)
            //System.out.println("-----------------jsonObject---------------- = " + jsonObject);
            //String trade_state = String.valueOf(jsonObject.get("trade_state"));
            if (parseResult.getTrade_state().equals("SUCCESS")) {
                //订单号
                String orderNumber = parseResult.getOut_trade_no();
                //-------------------修改订单状态已完成----------------------
                WbRepairOrder wbRepairOrder = new WbRepairOrder();
                wbRepairOrder.setVxpayOrdernumber(orderNumber);
                List<WbRepairOrder> wbRepairOrders = wbRepairOrderMapper.selectWbRepairOrderList(wbRepairOrder);
                if (!CollectionUtils.isEmpty(wbRepairOrders)) {
                    WbRepairOrder item = wbRepairOrders.get(0);
                    WbRepairApplyDto wbRepairApplyDto = new WbRepairApplyDto();
                    wbRepairApplyDto.setId(item.getApplyId());
                    wbRepairApplyDto.setStatus(WbRepairApplyOrderType.COMPLETED.getCode());//已完成
                    wbRepairApplyDto.setIfVx(true);
                    wbRepairApplyService.updateWbRepairApply(wbRepairApplyDto);
                }
                //-------------------修改订单状态已完成----------------------
                //微信支付微信生成的订单号
                // String transactionId = String.valueOf(jsonObject.get("transaction_id"));
                //  String outRefundNo= String.valueOf(jsonObject.get("out_refund_no"));
                //此处处理业务
                response.setStatus(200);
                map.put("code", "200");
                map.put("message", "成功");
                //消息推送成功
                return map;
            }

            map.put("code", "500");
            map.put("message", "订单不存在");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code", "500");
        map.put("message", "失败");
        return map;
    }

    /**
     * 统计当前维修师傅订单
     */
    @Override
    public OrderSummaryVo statisticsByUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return wbRepairOrderMapper.statisticsByUser(loginUser.getUserId());

    }


    @Transactional
    public Map<String, Object> payNotify1(HttpServletRequest request, HttpServletResponse response) {
        log.info("+++++++支付回调开始++++++++++++" + response);
        Map<String, Object> map = new HashMap<>();
        try {
            BufferedReader br = request.getReader();
            String str = null;
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            // 构建request，传入必要参数
            NotificationRequest requests = new NotificationRequest.Builder()
                    .withSerialNumber(request.getHeader("Wechatpay-Serial"))
                    .withNonce(request.getHeader("Wechatpay-Nonce"))
                    .withTimestamp(request.getHeader("Wechatpay-Timestamp"))
                    .withSignature(request.getHeader("Wechatpay-Signature"))
                    .withBody(String.valueOf(sb))
                    .build();
            //验签
            NotificationHandler handler = new NotificationHandler(WXPaySignatureCertificateUtil.getVerifier(WxV3PayConfig.mchSerialNo), WxV3PayConfig.apiV3Key.getBytes(StandardCharsets.UTF_8));
            //解析请求体
            Notification notification = handler.parse(requests);
            String decryptData = notification.getDecryptData();
            //解析
            JSONObject jsonObject = JSONObject.parseObject(decryptData);
            //支付状态交易状态，枚举值： SUCCESS：支付成功 REFUND：转入退款 NOTPAY：未支付 CLOSED：已关闭 REVOKED：已撤销（付款码支付）
            // USERPAYING：用户支付中（付款码支付） PAYERROR：支付失败(其他原因，如银行返回失败)
            String trade_state = String.valueOf(jsonObject.get("trade_state"));
            if (trade_state.equals("SUCCESS")) {
                //订单号
                String orderNumber = String.valueOf(jsonObject.get("out_trade_no"));
                System.out.println("orderNumber = " + orderNumber);
                //微信支付微信生成的订单号
                // String transactionId = String.valueOf(jsonObject.get("transaction_id"));
                //  String outRefundNo= String.valueOf(jsonObject.get("out_refund_no"));
                //此处处理业务
                map.put("code", "SUCCESS");
                map.put("message", "成功");
                //消息推送成功
                return map;
            }
            map.put("code", "RESOURCE_NOT_EXISTS");
            map.put("message", "订单不存在");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code", "FAIL");
        map.put("message", "失败");
        return map;
    }
}
